<script setup lang='ts'>
import {Splitpanes, Pane} from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import {computed, nextTick, onMounted, ref} from 'vue'
import {
  DocumentAdd,
  FolderAdd,
  DocumentDelete,
  Folder,
  Document,
  Edit,
  FolderDelete,
  Delete,
  Plus, Download, Upload, Operation
} from '@element-plus/icons-vue'
import {
  TemplateAddDTO, TemplateTreeDTO, TemplateUpdateDTO, SysTool, Item,
  getModeByName
} from '@/api/template/models'
import type Node from 'element-plus/es/components/tree/src/model/node'
import Codemirror from 'codemirror-editor-vue3'
import {
  addTemplateApi,
  deleteTemplateApi,
  getTreeApi,
  updateTemplateApi,
  updateTemplateContentApi,
  getTemplateContentByIdApi,
  tipsSystemToolApi,
  tipsFileInfoApi,
  tipsDataInfoApi,
  exportTemplateApi,
  importTemplateApi,
  updatePidApi,
  getOneTemplateApi
} from '@/api/template'
import {getEnumTemplateDynamicFieldApi} from '@/api/template-dynamic-field'
import {ElMessage, FormInstance, TabsPaneContext} from 'element-plus'
import {EditorConfiguration} from 'codemirror'
import 'codemirror/mode/javascript/javascript.js'
import 'codemirror/mode/css/css.js'
import 'codemirror/mode/htmlmixed/htmlmixed.js'
import 'codemirror/mode/apl/apl.js'
import 'codemirror/mode/sql/sql.js'
import 'codemirror/mode/yaml/yaml.js'
import 'codemirror/mode/clike/clike.js'
import 'codemirror/mode/python/python.js'
import 'codemirror/mode/go/go.js'
import 'codemirror/mode/php/php.js'
import 'codemirror/addon/display/autorefresh'
import "codemirror/theme/dracula.css"
import {listDataSourceApi} from "@/api/data-source";
import {format} from "date-fns";
import type {AllowDropType, NodeDropType} from "element-plus/es/components/tree/src/tree.type";
import type {DragEvents} from "element-plus/es/components/tree/src/model/useDragNode";
import {VueDraggable} from "vue-draggable-plus";

//是否打开详情弹窗
const dialogFormVisible = ref(false)
//是否打开删除确认弹窗
const deleteDialogFormVisible = ref(false)
//模板数据添加对象
const emptyTemplate = {
  id: '',
  pid: '',
  name: '',
  type: '',
  dynamicFields: [],
}
//模板数据修改对象
const templateUpdateData = ref<TemplateUpdateDTO>({...emptyTemplate})
//用于临时存储当前节点数据，用于删除当前节点数据
let tmpNode: Node
//用于删除当前节点数据
const tmpData = ref<TemplateTreeDTO>({...emptyTemplate})
//用于保存所有数据的对象
const dataSource = ref<TemplateTreeDTO[]>([])
//用于临时存储当前节点数据，用于数据修改
const currData = ref<TemplateTreeDTO>({...emptyTemplate})

// 全局列表，存储所有的打开的文件编辑对象
const itemMap = ref(new Map<string, Item>())
// 编辑区List，由itemMap转换而来
const itemList = computed(() => Array.from(itemMap.value.values()))
//当前编辑的文件id，组件名称
const currItemName = ref<string>('')

// 编辑区end
// 提示区start
// 提示对象
const systemTools = ref<SysTool[]>([])
const tipsFileInfo = ref<SysTool>({title: {code: '', tip: ''}, tips: [], children: []})
const enumTemplateDynamicField = ref()
//数据验证
const templateUpdateDataValid = ref<FormInstance>()

//添加文件夹
function addFolder() {
  //打开弹窗，输入名称，确定就保存
  dialogFormVisible.value = true
  templateUpdateData.value = {
    id: '',
    type: 'ml', //目录
    pid: 'root', //目录
    dynamicFields: [],
  }
}

//添加文件
function addDocument() {
  //打开弹窗，输入名称，确定就保存
  dialogFormVisible.value = true
  templateUpdateData.value = {
    id: '',
    type: 'wj', //文件
    pid: 'root',
    dynamicFields: [],
  }
}

//取消添加
function cancelEdit() {
  dialogBoxPostOperation()
}

//确认添加
function confirmEdit(formEl: FormInstance | undefined) {
  if (!formEl) return
  formEl.validate().then(() => {
    const tud = templateUpdateData.value
    if (!tud.id) {//id为空就添加，不为空则修改
      //执行添加操作
      addTemplateApi({...tud} as TemplateAddDTO).then(resp => {
        if (resp.data.code === 200) {
          const respData = resp.data.data as TemplateTreeDTO
          if ('root' == tud.pid) {
            (dataSource.value ||= []).push({...respData})
          } else {
            (currData.value.children ||= []).push({...respData})
            dataSource.value = [...dataSource.value]
          }

          ElMessage({type: 'success', message: '添加成功！'})
          // 关闭对话框
          dialogBoxPostOperation()
        }
      })

    } else {
      //执行修改操作
      updateTemplateApi({...tud}).then(resp => {
        if (resp.data.code === 200) {
          const item = itemMap.value.get(tud.id)
          if (tud.name) {
            currData.value.name = tud.name
            currData.value.zip = tud.zip;
            if (tud.skip !== null && tud.skip !== undefined) {
              currData.value.skip = tud.skip;
            }
            currData.value.unfoldField = tud.unfoldField
            currData.value.unfoldFieldAlias = tud.unfoldFieldAlias
            currData.value.reminder = tud.reminder
            if (item) item.title = tud.name
          }
          ElMessage({type: 'success', message: '修改成功！'})
          // 关闭对话框
          dialogBoxPostOperation()
        }
      })
    }
  })
}

//关闭对话框后置操作
function dialogBoxPostOperation() {
  //清空form
  templateUpdateData.value = {...emptyTemplate}
  currData.value = {...emptyTemplate}
  //关闭对话框
  dialogFormVisible.value = false
}

// 添加文件夹
function appendFolder(data: TemplateTreeDTO) {
  //打开弹窗，输入名称，确定就保存
  dialogFormVisible.value = true
  templateUpdateData.value = {
    type: 'ml',
    pid: data.id,
    id: '',
    dynamicFields: [],
  }
  currData.value = data
}

function appendDocument(data: TemplateTreeDTO) {
  //打开弹窗，输入名称，确定就保存
  dialogFormVisible.value = true
  templateUpdateData.value = {
    type: 'wj',
    pid: data.id,
    id: '',
    dynamicFields: [],
  }
  currData.value = data
}

function editDocument(data: TemplateTreeDTO) {
  //打开弹窗，输入名称，确定就保存
  dialogFormVisible.value = true
  getOneTemplateApi(data.id).then(resp => {
    templateUpdateData.value = resp.data.data
  })
  currData.value = data
}

//导出为zip
function exportTemplate(data: TemplateTreeDTO) {
  //打开弹窗，输入名称，确定就保存
  exportTemplateApi(data.id).then(resp => {
    // 创建 Blob 对象并触发下载
    const blob = new Blob([resp.data], {type: 'application/zip'});
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'SW_Templates_' + format(new Date(), "yyyy_MM_dd__HH_mm_ss_SSS") + '.zip'; // 文件名
    a.click();
    window.URL.revokeObjectURL(url);
  })
}

//导入zip模板
function importTemplate(data: TemplateTreeDTO) {
  // 创建隐藏的input元素触发文件选择
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.zip'
  input.onchange = async (e: Event) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (!file) return

    // 校验文件类型
    if (!file.name.endsWith('.zip')) {
      ElMessage.error('仅支持ZIP格式文件')
      return
    }

    // 构造FormData
    const formData = new FormData()
    formData.append('file', file)

    try {
      const resp = await importTemplateApi(data.id, formData)
      if (resp.data.code === 200) {
        ElMessage.success('模板导入成功')
        //请求接口，加载文件树
        getTreeApi('root').then(treeResp => {
          dataSource.value = treeResp.data.data
        })
      } else {
        ElMessage.error(resp.data.msg || '导入失败')
      }
    } catch (err) {
      ElMessage.error('请求失败，请检查网络')
    }
  }
  input.click()
}

//删除文件夹/文件
const remove = (node: Node, data: TemplateTreeDTO) => {
  deleteDialogFormVisible.value = true
  tmpNode = node
  tmpData.value = {...data}
}

const removeImpl = () => {
  let node: Node = tmpNode
  deleteTemplateApi(tmpData.value.id).then(resp => {
    if (resp.data.code === 200) {
      //从树删除节点
      const parent = node.parent
      const children: TemplateTreeDTO[] = parent.data.children || parent.data
      const index = children.findIndex((d) => d.id === tmpData.value.id)
      children.splice(index, 1)
      dataSource.value = [...dataSource.value]

      //关闭对话框
      deleteDialogFormVisible.value = false
      ElMessage({type: 'success', message: '删除成功！'})

      //从面包屑删除
      itemMap.value.delete(tmpData.value.id)

    }
  })
}

// 文件树end

// 编辑区start

function getOptions(fileName: string): EditorConfiguration {
  return {
    mode: {name: getModeByName(fileName)},
  }
}

function handleClick(event: MouseEvent, data: TemplateTreeDTO): void {
  //重新加载提示内容
  loadTipsFileInfo(data.id)
  // 判断是否是鼠标左键点击
  const newVar = itemMap.value.get(data.id)
  if (event.button === 0 // 左键
      && data.type === 'wj' //点击的内容为文件
      && !newVar // 没有打开过
  ) {
    //根据id请求内容后赋值
    getTemplateContentByIdApi(data.id)
        .then(resp => {
          data.content = resp.data.data
          itemMap.value.set(data.id, {
            name: data.id,
            isSaved: true,
            title: data.name,
            content: data.content ?? ''
          })
        }).finally(() => {
      // 设置当前面包屑
      setCurrItem(data.id)
    })
  } else {
    // 设置当前面包屑
    setCurrItem(data.id)
  }
}

// 4. 删除：根据 id 修改列表中的对象
function removeTab(name: string) {
  const item = itemMap.value.get(name)
  if (item) {
    if (item.isSaved) {
      itemMap.value.delete(name)
      if (name === currItemName.value) {
        if (itemList.value.length) {
          currItemName.value = itemList.value[itemList.value.length - 1].name
        } else currItemName.value = ''
      }
    } else ElMessage({type: 'warning', message: '暂未保存，不能移除！按【ctrl+s】保存'})
  }
}

// 4. 选中：根据 id 修改列表中的对象
function tabClick(pane: TabsPaneContext) {
  setCurrItem(pane.paneName as string)
}

// 保存内容 ctrl+s
function handleCtrlS(event: KeyboardEvent, id: string) {
  if (event.ctrlKey && event.key === 's') {
    event.preventDefault()
    saveItem(id)
  }
}

// 5. 保存：ctrl+s调用第三方 API 进行保存操作
async function saveItem(id: string): Promise<boolean> {
  const item = itemMap.value.get(id)
  if (item) {
    // 模拟调用第三方 API 保存操作
    try {
      // 假设我们有一个保存的 API，返回一个 Promise
      return await updateTemplateContentApi({
        id: item.name,
        content: item.content
      }).then(() => {
        item.isSaved = true  // 保存成功后，标记为已保存
        return true
      })
    } catch (error) {
      return false
    }
  }
  return false
}

// 7. 切换当前item
function setCurrItem(id: string) {
  const item: Item | undefined = itemMap.value.get(id)
  if (item) {
    currItemName.value = item.name
  }

  //处理动态编辑器闪动问题
  nextTick(() => {
    // 通过 DOM ID 获取 CodeMirror 实例
    const cmInstance = (document.getElementById(id as string)?.querySelector('.CodeMirror') as any)?.CodeMirror;
    // 使用 setTimeout 确保 DOM 更新完成
    setTimeout(() => cmInstance?.refresh(), 50);
  });
}

//删除动态字段
function deleteDynamicField(index: number) {
  if (templateUpdateData.value.dynamicFields) {
    templateUpdateData.value.dynamicFields.splice(index, 1)
  }
}

//追加动态字段
function addDynamicField() {
  if (!templateUpdateData.value.dynamicFields) {
    templateUpdateData.value.dynamicFields = []
  }
  templateUpdateData.value.dynamicFields.push({
    name: '',
    placeholder: '',
    type: 'string',
    content: ''
  })
}

//加载文件提示
function loadTipsFileInfo(templateId: string) {
  tipsFileInfoApi(templateId).then(resp => {
    tipsFileInfo.value = resp.data.data
  })
}

// 提示区end

const state = ref('')
const loading = ref(false) // 控制加载状态
const modeList = ["view"]
const currentMode = 'view'
const dataSourceInfo = ref()

interface LinkItem {
  value: string
  id: string
}

const timeout = ref<NodeJS.Timeout | null>(null)

const querySearchAsync = async (queryString: string, cb: (arg: any) => void) => {
  if (timeout.value) {
    clearTimeout(timeout.value)
  }

  // 延时 200ms 后执行 API 请求
  timeout.value = setTimeout(async () => {
    loading.value = true
    await listDataSourceApi({name: queryString, current: 1, size: 10})
        .then(resp => {
          const suggestions = resp.data.data.map((item: any) => ({
            value: item.name,
            id: item.id,
          }))
          cb(suggestions) // 返回数据给下拉组件
        }).catch(() => {
          cb([]) // 请求失败时返回空数据
        }).finally(() => {
          loading.value = false
        })
  }, 100) // 延时 200ms
}

const handleSelect = (item: LinkItem) => {
  //调用数据源提示接口
  tipsDataInfoApi(item.id)
      .then(resp => {
        dataSourceInfo.value = resp.data.data
      })
}

//判断是否允许拖动
const allowDrop = (_draggingNode: Node, dropNode: Node, type: AllowDropType) => {
  if (type === 'inner') {
    return dropNode.data.type !== 'wj';
  } else return true
}
const handleDrop = (
    draggingNode: Node,
    dropNode: Node,
    dropType: NodeDropType,
    _ev: DragEvents
) => {
  if (dropType === 'before' || dropType === 'after') {
    //把draggingNode的pid设置为dropNode的pid
    updatePidApi(draggingNode.data.id, dropNode.data.pid).then(() => {
      //刷新树
      refreshTree()
    })
  } else if (dropType === 'inner') {
    //把draggingNode的pid设置为dropNode的id
    updatePidApi(draggingNode.data.id, dropNode.data.id).then(() => {
      //刷新树
      refreshTree()
    })
  }
}

function refreshTree() {
  //请求接口，加载文件树
  getTreeApi('root').then(resp => {
    dataSource.value = resp.data.data
  })
}

//加载数据
onMounted(() => {
  //请求接口，加载文件树
  refreshTree()
  //加载系统工具提示
  tipsSystemToolApi().then(resp => {
    systemTools.value = resp.data.data
  })
  //加载文件提示
  loadTipsFileInfo(currItemName.value)
  //加载数据源提示
  tipsDataInfoApi('').then(resp => {
    dataSourceInfo.value = resp.data.data
  })
  //加载动态字段枚举
  getEnumTemplateDynamicFieldApi().then(resp => {
    enumTemplateDynamicField.value = resp.data.data
  })
})
</script>

<template>
  <div>
    <!--分割线框架-->
    <splitpanes class="default-theme">
      <!--文件区-->
      <pane min-size="1" size="25">
        <!--文件区头部-->
        <div class="file-area-header">
          <el-tooltip
              class="box-item"
              effect="dark"
              content="添加根 文件夹"
              placement="top"
          >
            <el-button :icon="FolderAdd" circle @click="addFolder"/>
          </el-tooltip>
          <el-tooltip
              class="box-item"
              effect="dark"
              content="添加根 文件"
              placement="top"
          >
            <el-button :icon="DocumentAdd" circle @click="addDocument"/>
          </el-tooltip>
        </div>
        <hr/>
        <div class="file-area-body">
          <el-scrollbar height="76vh">
            <el-tree
                :allow-drop="allowDrop"
                :data="dataSource"
                draggable
                default-expand-all
                node-key="id"
                highlight-current
                :expand-on-click-node="false"
                @node-drop="handleDrop"
            >
              <template #default="{ node, data }">
                <el-col :span="8">
                  <el-dropdown trigger="contextmenu">
                    <span class="el-dropdown-link" @click="handleClick($event,data)">
                      <el-icon v-if="data.type === 'ml'"><Folder/></el-icon>
                      <el-icon v-if="data.type === 'wj'"><Document/></el-icon>
                      {{ data.name }}
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                            v-if="data.type === 'ml'"
                            :icon="FolderAdd"
                            @click="appendFolder(data)"
                        >添加文件夹
                        </el-dropdown-item>
                        <el-dropdown-item
                            v-if="data.type === 'ml'"
                            :icon="DocumentAdd"
                            @click="appendDocument(data)"
                        >添加文件
                        </el-dropdown-item>
                        <el-dropdown-item
                            :icon="Edit"
                            @click="editDocument(data)"
                        >修改
                        </el-dropdown-item>
                        <el-dropdown-item
                            :icon="Download"
                            @click="exportTemplate(data)"
                        >导出
                        </el-dropdown-item>
                        <el-dropdown-item
                            v-if="data.type === 'ml'"
                            :icon="Upload"
                            @click="importTemplate(data)"
                        >导入
                        </el-dropdown-item>
                        <el-dropdown-item
                            :icon="DocumentDelete"
                            @click="remove(node,data)"
                        >删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-col>
              </template>
            </el-tree>
          </el-scrollbar>
        </div>
      </pane>
      <!--编辑区-->
      <pane min-size="1" size="50">
        <!--v-model为当前节点-->
        <el-tabs
            v-if="currItemName"
            v-model="currItemName"
            closable
            @tab-remove="removeTab"
            @tab-click="tabClick"
        >
          <el-tab-pane
              v-for="item in itemList"
              :key="item.name"
              :label="item.title"
              :name="item.name"
          >
            <template #label>
              <span class="custom-tabs-label">
                <span>{{ item.title }}</span>
                <el-icon v-if="!item.isSaved"><Edit/></el-icon>
              </span>
            </template>
            <div
                class="editor-body"
                @keydown="handleCtrlS($event,item.name)"
                tabindex="0"
            >
              <Codemirror
                  :id="item.name"
                  v-model:value="item.content"
                  height="74vh"
                  border
                  @change="item.isSaved = false"
                  :options="getOptions(item.title)"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </pane>
      <!--提示区-->
      <pane min-size="1" size="30">
        <div class="tips-header">
          <span>数据与工具 代码提示</span>
        </div>
        <hr/>
        <div class="tips-body">
          <el-scrollbar height="76vh">
            <el-collapse :v-model="1">
              <!-- 数据相关折叠栏 -->
              <el-collapse-item name="1"> <!--选择数据源，不选则使用默认的结构-->
                <template #title>
                  <strong>数据源</strong>
                  <el-autocomplete
                      v-model="state"
                      :fetch-suggestions="querySearchAsync"
                      placeholder="搜索数据源"
                      @select="handleSelect"
                      style="width: 150px;margin-left: 20px"
                  />
                </template>
                <div>
                  <json-editor-vue
                      class="editor"
                      v-model="dataSourceInfo"
                      :currentMode="currentMode"
                      :modeList="modeList"/>
                </div>
              </el-collapse-item>

              <!-- 文件相关折叠栏 -->
              <el-collapse-item name="2"><!--根据当前编辑框获取文件提示列表-->
                <template #title>
                  <el-tooltip
                      :content="tipsFileInfo.title.tip" placement="right"
                      effect="light"
                  >
                    <strong>模板文件</strong>
                  </el-tooltip>
                </template>
                <el-tooltip
                    v-for="(l,li) in tipsFileInfo.tips"
                    :key="li"
                    :content="l.tip" placement="right"
                    effect="light"
                >
                  <p><code>{{ l.code }}</code></p>
                </el-tooltip>
                <el-collapse-item
                    v-for="(st ,si) in tipsFileInfo.children"
                    :key="si"
                    :name="si">
                  <template #title>
                    <el-tooltip
                        :content="st.title.tip"
                        placement="left"
                        effect="light"
                    >
                      <strong>{{ st.title.code }}</strong>
                    </el-tooltip>
                  </template>
                  <div>
                    <el-tooltip
                        v-for="(l,li) in st.tips"
                        :key="li"
                        :content="l.tip"
                        placement="right"
                        effect="light"
                    >
                      <p style="padding-left: 13px"><code>{{ l.code }}</code></p>
                    </el-tooltip>
                  </div>
                </el-collapse-item>
              </el-collapse-item>

              <!-- 系统工具折叠栏 -->
              <el-collapse-item name="3">
                <template #title>
                  <strong>系统工具</strong>
                </template>
                <el-collapse :v-model="1" style="padding-left: 20px">
                  <el-collapse-item
                      v-for="(st ,si) in systemTools"
                      :key="si"
                      :name="si">
                    <template #title>
                      <el-tooltip
                          :content="st.title.tip"
                          placement="left"
                          effect="light"
                      >
                        <strong>{{ st.title.code }}</strong>
                      </el-tooltip>
                    </template>
                    <div>
                      <el-tooltip
                          v-for="(l,li) in st.tips"
                          :key="li"
                          :content="l.tip"
                          placement="right"
                          effect="light"
                      >
                        <p style="padding-left: 13px"><code>{{ l.code }}</code></p>
                      </el-tooltip>
                    </div>
                  </el-collapse-item>
                </el-collapse>

              </el-collapse-item>
            </el-collapse>
          </el-scrollbar>

        </div>
      </pane>
    </splitpanes>
    <!--其他功能区-->
    <div>
      <!--添加弹框对话框-->
      <div>
        <el-dialog v-model="dialogFormVisible"
                   width="1000"
                   :modal="false"
                   center
                   draggable
        >
          <el-icon class="editDialog" v-if="!templateUpdateData.id && templateUpdateData.type === 'ml'">
            <FolderAdd/>
          </el-icon>
          <el-icon class="editDialog" v-if="!templateUpdateData.id && templateUpdateData.type === 'wj'">
            <DocumentAdd/>
          </el-icon>
          <el-icon class="editDialog" v-if="templateUpdateData.id">
            <Edit/>
          </el-icon>
          <br/>
          <span>加载顺序：展开字段 => 字段别名 => 动态字段 => 模板名称、是否压缩表达式、是否跳过表达式</span>
          <br/>
          <br/>
          <el-form :model="templateUpdateData"
                   ref="templateUpdateDataValid"
                   :inline="true">
            <el-form-item label="展开字段" label-width="100px">
              <el-input
                  style="width: 868px"
                  v-model="templateUpdateData.unfoldField" autocomplete="off"
                  autosize
                  type="textarea"
                  placeholder="用于展开遍历的字段"/>
            </el-form-item>
            <el-form-item label="字段别名"
                          prop="unfoldFieldAlias"
                          :rules="{required: templateUpdateData.unfoldField,message: '字段别名不能为空！'}"
                          label-width="100px">
              <el-input
                  style="width: 868px"
                  v-model="templateUpdateData.unfoldFieldAlias" autocomplete="off"
                  autosize
                  type="textarea"
                  placeholder="展开后的别名"/>
            </el-form-item>
            <el-form-item label="模板名称"
                          prop="name"
                          :rules="{required: true,message: '名称不能为空！'}"
                          label-width="100px">
              <el-input
                  style="width: 868px"
                  v-model="templateUpdateData.name" autocomplete="off"
                  autosize
                  type="textarea"
                  placeholder="名称可以是模板语法占位符。"/>
            </el-form-item>
            <el-form-item label="是否压缩为zip" label-width="100px" style="display: none">
              <el-input
                  style="width: 868px"
                  v-model="templateUpdateData.zip" autocomplete="off"
                  autosize
                  type="textarea"
                  placeholder="压缩为zip的模板表达式。"/>
            </el-form-item>
            <el-form-item label="是否跳过" label-width="100px">
              <el-input
                  style="width: 868px"
                  v-model="templateUpdateData.skip" autocomplete="off"
                  autosize
                  type="textarea"
                  placeholder="是否跳过的模板表达式。"/>
            </el-form-item>
            <el-form-item label="提示说明" label-width="100px">
              <el-input
                  style="width: 868px"
                  v-model="templateUpdateData.reminder" autocomplete="off"
                  autosize
                  type="textarea"
                  placeholder="该模板的提示说明。"/>
            </el-form-item>
            <br/>
            <strong>动态字段</strong>
            <VueDraggable
                target="tbody"
                v-model="templateUpdateData.dynamicFields"
                :animation="150"
                :handle="'.drag-handle'"
            >
              <el-table :data="templateUpdateData.dynamicFields" style="width: 100%" max-height="100%">

                <!-- 将名称列修改为输入框 -->
                <el-table-column label="名称" width="150">
                  <template #default="scope">
                    <el-form-item style="display: block !important; margin-bottom: 0; width: 130px"
                                  :prop="`dynamicFields.${scope.$index}.name`"
                                  :rules=" {required: true}">
                      <el-input
                          v-model="scope.row.name"
                          placeholder="请输入名称"
                          autosize
                          type="textarea"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>

                <!-- 将占位符列修改为输入框 -->
                <el-table-column label="占位符（非空）" width="200">
                  <template #default="scope">
                    <el-form-item style="display: block !important; margin-bottom: 0; width: 180px"
                                  :prop="`dynamicFields.${scope.$index}.placeholder`"
                                  :rules=" {required: true}">
                      <el-input
                          v-model="scope.row.placeholder"
                          placeholder="请输入占位符"
                          autosize
                          type="textarea"
                      />
                    </el-form-item>
                  </template>
                </el-table-column>

                <!-- 占位符类型为下拉框 -->
                <el-table-column label="类型" width="120">
                  <template #default="scope">
                    <el-select
                        v-model="scope.row.type"
                        placeholder="请选择类型"
                    >
                      <el-option
                          v-for="item in enumTemplateDynamicField['type']"
                          :key="item.code"
                          :label="item.label"
                          :value="item.value"
                      />
                    </el-select>
                  </template>
                </el-table-column>

                <!-- 将默认值列修改为输入框 -->
                <el-table-column label="默认值">
                  <template #default="scope">
                    <el-input
                        v-model="scope.row.content"
                        v-if="scope.row.type==='string'"
                        autosize
                        type="textarea"
                        placeholder="请输入默认值"
                    />
                    <el-input
                        v-model="scope.row.content"
                        v-else-if="scope.row.type==='number'"
                        type="number"
                        placeholder="请输入默认值"
                    />
                    <el-select
                        v-model="scope.row.content"
                        v-else-if="scope.row.type==='boolean'"
                        placeholder="请选择类型"
                    >
                      <el-option key="true" label="是" value="true"/>
                      <el-option key="false" label="否" value="false"/>
                    </el-select>
                  </template>
                </el-table-column>

                <el-table-column fixed="right" label="操作" min-width="17">
                  <template #default="scope">
                    <div>
                      <el-button
                          link
                          type="primary"
                          size="small"
                          @click.prevent="deleteDynamicField(scope.$index)"
                          :icon="Delete"
                      />
                      <el-button link
                                 type="primary"
                                 size="small"
                                 :icon="Operation"
                                 class="drag-handle"
                      />
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </VueDraggable>

            <el-button class="mt-4" style="width: 100%" @click="addDynamicField">
              <el-icon>
                <Plus/>
              </el-icon>
            </el-button>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="cancelEdit">取消</el-button>
              <el-button type="primary" @click="confirmEdit(templateUpdateDataValid)">确定</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
      <!--删除确认框-->
      <div>
        <el-dialog
            v-model="deleteDialogFormVisible"
            title="确认是否删除"
            width="500"
            center
        >
          <el-icon class="editDialog" v-if="tmpData.type === 'ml'">
            <FolderDelete/>
          </el-icon>
          <el-icon class="editDialog" v-if="tmpData.type === 'wj'">
            <DocumentDelete/>
          </el-icon>
          <br/>
          <span>注意：删除后不可恢复！</span>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="deleteDialogFormVisible = false">取消</el-button>
              <el-button type="danger" @click="removeImpl">删除</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<style scoped>

.editDialog {
  position: absolute;
  top: 10px;
  left: 10px;
  font-size: 30px; /* 放大图标 */
  z-index: 10; /* 保证图标在对话框的最上层 */
}

.file-area-body {
  height: 100%;
  overflow: hidden; /* 确保没有父容器溢出隐藏 */
}

/*设置头部样式*/
.file-area-header, .tips-header {
  height: 5vh;
}

:deep(.jsoneditor-frame) {
  display: none;
}

:deep(.jsoneditor-menu>.jsoneditor-modes) {
  display: none;
}

:deep(.jsoneditor-menu) {
  width: 100%;
  height: 32px;
  padding: 2px;
  margin: 0;
  box-sizing: border-box;
  color: #fff;
  background-color: #c1c1c1;
  border-bottom: 1px solid #3883fa;
}

.drag-handle {
  cursor: ns-resize;
}
</style>